package com.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseAppV1;
import com.atguigu.gmall.realtime.bean.TradeOrderBean;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.DateFormatUtil;
import com.atguigu.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2022/5/8 22:33
 */
public class Dws_07_DwsTradeOrderWindowApp extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_07_DwsTradeOrderWindowApp().init(
            "Dws_7_DwsTradeOrderWindowApp",
            4007,
            1,
            "Dws_7_DwsTradeOrderWindowApp",
            "Dws_7_DwsTradeOrderWindowApp",
            "dwd_trade_order_detail"
        );
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1. 对order_detail_id 相同的数据去重, 保留数据最全的记录
        SingleOutputStreamOperator<JSONObject> distinctedStream = distinctByOrderId(stream);  // 去重
        
        // 2. 当日独立用户和新增用户
        SingleOutputStreamOperator<TradeOrderBean> tradeOrderBeanStream = parseToTradeOrderBean(distinctedStream);
        
        // 3. 统计指标: 下单独立用户数 新单新用户 下单活动减免金额 下单优惠券减免金额 下单原始金额
        SingleOutputStreamOperator<TradeOrderBean> resultStream = windowAndAgg(tradeOrderBeanStream);
        
        // 4. 数据写出到clickhouse中
        writeToClickhouse(resultStream);
    }
    
    private void writeToClickhouse(SingleOutputStreamOperator<TradeOrderBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil
                                 .getClickHouseSink(Constant.CLICKHOUSE_DB, "dws_trade_order_window", TradeOrderBean.class));
    }
    
    private SingleOutputStreamOperator<TradeOrderBean> windowAndAgg(SingleOutputStreamOperator<TradeOrderBean> stream) {
        return stream
            .windowAll(TumblingEventTimeWindows.of(Time.seconds(10)))
            .reduce(
                new ReduceFunction<TradeOrderBean>() {
                    @Override
                    public TradeOrderBean reduce(TradeOrderBean tob1,
                                                 TradeOrderBean tob2) throws Exception {
                        tob1.setOrderUniqueUserCount(tob1.getOrderUniqueUserCount() + tob2.getOrderUniqueUserCount());
                        tob1.setOrderNewUserCount(tob1.getOrderNewUserCount() + tob2.getOrderNewUserCount());
                        tob1.setOrderActivityReduceAmount(tob1.getOrderActivityReduceAmount() + tob2.getOrderActivityReduceAmount());
                        tob1.setOrderCouponReduceAmount(tob1.getOrderCouponReduceAmount() + tob2.getOrderCouponReduceAmount());
                        tob1.setOrderOriginalTotalAmount(tob1.getOrderOriginalTotalAmount() + tob2.getOrderOriginalTotalAmount());
                        
                        return tob1;
                    }
                },
                new AllWindowFunction<TradeOrderBean, TradeOrderBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window,
                                      Iterable<TradeOrderBean> values,
                                      Collector<TradeOrderBean> out) throws Exception {
                        String stt = DateFormatUtil.toYmdHms(window.getStart());
                        String edt = DateFormatUtil.toYmdHms(window.getEnd());
    
    
                        TradeOrderBean tob = values.iterator().next();
                        tob.setStt(stt);
                        tob.setEdt(edt);
                        tob.setTs(System.currentTimeMillis());
                        
                        out.collect(tob);
                    }
                }
            );
        
    }
    
    private SingleOutputStreamOperator<TradeOrderBean> parseToTradeOrderBean(
        SingleOutputStreamOperator<JSONObject> stream) {
        return stream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("ts") * 1000)
            )
            .keyBy(obj -> obj.getString("user_id"))
            .process(new KeyedProcessFunction<String, JSONObject, TradeOrderBean>() {
                
                private ValueState<String> lastOrderDateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    lastOrderDateState = getRuntimeContext()
                        .getState(new ValueStateDescriptor<String>("lastOrderDateState", String.class));
                }
                
                @Override
                public void processElement(JSONObject value,
                                           Context ctx,
                                           Collector<TradeOrderBean> out) throws Exception {
                    /*
                    如何统计今天下单独立用户和新增用户:
                        状态存储改用户上次登录日期.
                            如果状态为空,
                                则为新增用户和今天独立下单用户
                            
                            如果状态不为空且与今天不同
                                则为今天独立下单用户
                                
                          要更新状态
                     */
                    TradeOrderBean bean = new TradeOrderBean();
                    // 如果没有减免金额就设置为 0
                    Double splitActivityAmount = value.getDouble("split_activity_amount");
                    if (splitActivityAmount != null) {
                        bean.setOrderActivityReduceAmount(splitActivityAmount);
                    }
                    
                    Double splitCouponAmount = value.getDouble("split_coupon_amount");
                    if (splitCouponAmount != null) {
                        bean.setOrderCouponReduceAmount(splitCouponAmount);
                    }
                    // 原始金额一定有, 可以不用判断
                    bean.setOrderOriginalTotalAmount(value.getDouble("split_original_amount"));
                    bean.setTs(value.getLong("ts"));
                    
                    String lastOrderDate = lastOrderDateState.value();
                    
                    if (lastOrderDate == null) {
                        bean.setOrderUniqueUserCount(1L);
                        bean.setOrderNewUserCount(1L);
                        // 更新状态  date_id在前面已经计算过日期了
                        lastOrderDateState.update(value.getString("date_id"));
                    } else {
                        // 如果状态不为空, 且与今天不等, 则为今天独立下单用户
                        if (!lastOrderDate.equals(value.getString("date_id"))) {
                            bean.setOrderUniqueUserCount(1L);
                            lastOrderDateState.update(value.getString("date_id"));
                        }
                    }
                    out.collect(bean);
                }
            });
    }
    
    private SingleOutputStreamOperator<JSONObject> distinctByOrderId(DataStreamSource<String> stream) {
        /*
            由于前面(预处理表)左连接的存在, 同一个order_detail_id会有多条数据, 要保留数据最全的那条记录
            
        时间最晚的数据最全
         row_op_ts 表示数据的生成时间  2022-05-08 15:30:56.723Z   row_op_ts":"2022-05-08 15:30:56.72Z
         */
        return stream
            .map(JSON::parseObject)
            .keyBy(obj -> obj.getLong("id"))
            .process(new KeyedProcessFunction<Long, JSONObject, JSONObject>() {
                // 存储数据最全的状态
                private ValueState<JSONObject> lastDataState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    lastDataState = getRuntimeContext().getState(new ValueStateDescriptor<JSONObject>("lastDataState", JSONObject.class));
                }
                
                @Override
                public void processElement(JSONObject data,
                                           Context ctx,
                                           Collector<JSONObject> out) throws Exception {
                    JSONObject lastData = lastDataState.value();
                    if (lastData == null) {
                        // 把数据存入到状态中, 并定义定时器
                        lastDataState.update(data);
                        
                        ctx.timerService().registerProcessingTimeTimer(ctx.timerService().currentProcessingTime() + 5000);
                    } else {
                        // 2022-05-08 15:30:56.723Z   row_op_ts":"2022-05-08 15:30:56.72Z
                        String currentTime = data.getString("row_op_ts");
                        String lastTime = lastData.getString("row_op_ts");
                        // 新数据的生成时间是否 大于 状态中的数据的生成时间
                        boolean isGreatOrEqual = AtguiguUtil.compareLTZ(currentTime, lastTime);
                        if (isGreatOrEqual) {
                            // 更新状态
                            lastDataState.update(data);
                        }
                    }
                }
                
                @Override
                public void onTimer(long timestamp,
                                    OnTimerContext ctx,
                                    Collector<JSONObject> out) throws Exception {
                    out.collect(lastDataState.value());
                }
            });
    }
}
